package com.en.utils;

import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson2.JSON;
import com.en.response.AppException;
import com.en.response.ErrorCodeMsgEnum;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.RequestBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;

/**
 * @Description: 各种工具类
 * @Author: wht
 * @Date: 2023-12-24
 */
@Slf4j
public class Tools {
    public static String httpGet(String url) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).get().build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (Exception e) {
            throw new AppException(ErrorCodeMsgEnum.SERVICE_ERROR);
        }
    }

    public static String httpPost(String url, Map body) {
        try {
            MediaType JSON_TYPE = MediaType.parse("application/json; charset=utf-8");
            OkHttpClient client = new OkHttpClient();

            RequestBody requestBody = RequestBody.create(JSON_TYPE, JSON.toJSONString(body));
            Request request = new Request.Builder().url(url).post(requestBody).build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            throw new AppException(ErrorCodeMsgEnum.SERVICE_ERROR);
        }
    }

    //    微信公众号验证服务器token
    public static Boolean CheckSignature(String token, String signature, String timestamp, String nonce) {
        String[] ArrTmp = {token, timestamp, nonce};
        //字典排序
        Arrays.sort(ArrTmp);
        //拼接
        String tmpStr = String.join("", ArrTmp);
        //sha1验证
        String sha1 = DigestUtil.sha1Hex(tmpStr);

        return sha1.toLowerCase() == signature;
    }

    // 获取请求头里的数据
    public static String getRequestBody(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        try {
            ServletInputStream inputStream = request.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            log.error("读取数据流异常:{}", e);
        }
        return sb.toString();
    }


    public static String getWordFullPath(String outputDirectory, String word) {
        String word_no_blank = word.replaceAll(" ", "").toLowerCase();

        String subPath = "";
        try {
            for (int i = 0; i < 3; i++) {
                String letter = String.valueOf(word_no_blank.charAt(i));
                subPath += "/" + letter;
            }
        } catch (Exception e) {
            log.info("outputDirectory:" + subPath);
        }


//        String letter0;
//        String letter1;
//        String letter2;
//
//        try {
//            letter0 = String.valueOf(word_no_blank.charAt(0));
//            letter1 = String.valueOf(word_no_blank.charAt(1));
//            letter2 = String.valueOf(word_no_blank.charAt(2));
//        } catch (Exception e) {
//
//        }
//
//        String subPath;
//        if (word_no_blank.length() == 1) {
//            subPath = letter0 + "/" + letter0 + "/" + letter0;
//        } else if (word_no_blank.length() == 2) {
//            subPath = letter0 + "/" + letter1 + "/" + letter1;
//        } else {
//            subPath = letter0 + "/" + letter1 + "/" + letter2;
//        }

        String fullDirectory = outputDirectory + subPath;

        Path directoryPath = Paths.get(fullDirectory);
        if (!Files.isDirectory(directoryPath)) {
            try {
                Files.createDirectories(directoryPath);
            } catch (Exception e) {
                throw new RuntimeException("文件创建失败");
            }
        }

        return fullDirectory + "/" + word_no_blank + ".wav";
    }


    public static String getZhFullPath(String outputDirectory, String chinese) {
        String sha1 = DigestUtil.sha1Hex(chinese);

        String subPath = "";
        for (int i = 0; i < 3; i++) {
            String letter = String.valueOf(sha1.charAt(i));
            subPath += "/" + letter;
        }

        String fullDirectory = outputDirectory + subPath;

        Path directoryPath = Paths.get(fullDirectory);
        if (!Files.isDirectory(directoryPath)) {
            try {
                Files.createDirectories(directoryPath);
            } catch (Exception e) {
                throw new RuntimeException("文件创建失败");
            }
        }

        return fullDirectory + "/" + sha1 + ".wav";
    }
}

